//
//  FMDiantaiPlayViewController.m
//  PsychologyFM
//
//  Created by lanou on 16/1/13.
//  Copyright © 2016年 ZhangLuDu. All rights reserved.
//

#import "FMDiantaiPlayViewController.h"
#import "FMDiantaiPlayView.h"
#import "FMLessonAndFMModel.h"
#import <UIImageView+WebCache.h>
#import <UIButton+WebCache.h>
#import "PKMusicPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import "FMAntorDescViewController.h"

@interface FMDiantaiPlayViewController ()

@property (nonatomic,strong) FMDiantaiPlayView *diantaiPlayView;

@property (nonatomic,strong) FMLessonAndFMModel *model;

@property (nonatomic, strong) AVPlayer *player1;

@property (nonatomic,strong) UIButton *sendGiftButton;
@property (nonatomic,strong) UIButton *commentButton;
@property (nonatomic,strong) UIButton *zanButton;
@property (nonatomic,strong) UIButton *shareButton;
@property (nonatomic,strong) UIButton *moreButton;
@property (nonatomic,assign) BOOL isPlayer;     // 判断电台是否正在播放
@property (nonatomic,strong) UILabel *sendGiftLabel;
@property (nonatomic,strong) UILabel *commentLabel;
@property (nonatomic,strong) UILabel *zanLabel;
@property (nonatomic,strong) UILabel *shareLabel;
@property (nonatomic,strong) UILabel *moreLabel;
@property (nonatomic, strong)NSMutableDictionary *dataDic;
@property (nonatomic,strong) UIImageView *moreImgView;
@property (nonatomic, strong) PKMusicPlayer *player;
@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic, assign)NSInteger totalTime;
@property (nonatomic, strong)NSMutableArray *musicArray;
@property (nonatomic, assign)int i;
@end

@implementation FMDiantaiPlayViewController

#pragma mart ---  视图将要出现时
- (void)viewWillAppear:(BOOL)animated
{

    //  隐藏导航栏
    self.navigationController.navigationBar.hidden = YES;
    //  取出tabBar让其隐藏,页面消失时出现
    _rootVC.tabbar.hidden = YES;
    
    //  取出tabBar让其隐藏,页面出现时消失
    _rootVC.tabbar.hidden = NO;
    
    _sendGiftButton.hidden = NO;
    _commentButton.hidden = NO;
    _zanButton.hidden = NO;
    _shareButton.hidden = NO;
    _moreButton.hidden = NO;
    
    
    
}


#pragma mart ---  视图已经加载
- (void)viewDidLoad {
    _dataDic = [NSMutableDictionary dictionary];
    _i = 0;
    _isPlayer = YES;
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //  不允许自动布局
    self.automaticallyAdjustsScrollViewInsets = NO;
    
     [_diantaiPlayView.playButton setBackgroundImage:[UIImage imageNamed:@"play"] forState:(UIControlStateNormal)];
    
    self.view.backgroundColor = FMWhite;
    
    _diantaiPlayView = [[FMDiantaiPlayView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.view addSubview:_diantaiPlayView];
    
    [self addBottomButtons];
    
    //  请求数据
    [self requestData];
    
    //  为按钮添加方法
    //  返回按钮
    [_diantaiPlayView.backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    

    //  送礼物按钮
    [_sendGiftButton addTarget:self action:@selector(sendButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    //  评论按钮
    [_commentButton addTarget:self action:@selector(commentButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    //  赞按钮
    [_zanButton addTarget:self action:@selector(zanButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    //  分享按钮
    [_shareButton addTarget:self action:@selector(shareButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    //  更多按钮
    [_moreButton addTarget:self action:@selector(moreButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    if (_isPlayer == YES) {
        [_player1 play];
        _isPlayer = NO;
        [_diantaiPlayView.playButton setBackgroundImage:[UIImage imageNamed:@"play"] forState:(UIControlStateNormal)];
       }
    
    
    
     _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(playerPlaying:) userInfo:nil repeats:YES];
    

}
#pragma  mark 添加底部按钮
- (void)addBottomButtons
{
    //  在界面将要出现的时候在_rootVC上加按钮
    //  view底部的按钮和Label
    //  送礼物
    _sendGiftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _sendGiftButton.frame = CGRectMake(0, kScreenHeight - 49, kScreenWidth / 5, 49);
    [_sendGiftButton setImage:[UIImage imageNamed:@"gift1@2x"] forState:(UIControlStateNormal)];
    [_rootVC.view addSubview:_sendGiftButton];
    
    _sendGiftLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, _sendGiftButton.width, 19)];
    _sendGiftLabel.text = @"送礼物";
    _sendGiftLabel.textColor = FMWhite;
    _sendGiftLabel.font = [UIFont systemFontOfSize:12];
    _sendGiftLabel.textAlignment = NSTextAlignmentCenter;
    [_sendGiftButton addSubview:_sendGiftLabel];
    
    //  评论
    _commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _commentButton.frame = CGRectMake(_sendGiftButton.right, kScreenHeight - 49, kScreenWidth / 5, 49);
    [_commentButton setImage:[UIImage imageNamed:@"comment1@2x"] forState:(UIControlStateNormal)];
    [_rootVC.view addSubview:_commentButton];
    
    _commentLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, _commentButton.width, 19)];
    _commentLabel.text = @"评论:777";
    _commentLabel.textColor = FMWhite;
    _commentLabel.font = [UIFont systemFontOfSize:12];
    _commentLabel.textAlignment = NSTextAlignmentCenter;
    [_commentButton addSubview:_commentLabel];
    
    //  赞
    _zanButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _zanButton.frame = CGRectMake(_commentButton.right, kScreenHeight - 49, kScreenWidth / 5, 49);
    [_zanButton setImage:[UIImage imageNamed:@"zan"] forState:(UIControlStateNormal)];
    [_rootVC.view addSubview:_zanButton];
    
    _zanLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, _commentButton.width, 19)];
    _zanLabel.text = @"赞:777";
    _zanLabel.textColor = FMWhite;
    _zanLabel.font = [UIFont systemFontOfSize:12];
    _zanLabel.textAlignment = NSTextAlignmentCenter;
    [_zanButton addSubview:_zanLabel];
    
    //  分享
    _shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _shareButton.frame = CGRectMake(_zanButton.right, kScreenHeight - 49, kScreenWidth / 5, 49);
    [_shareButton setImage:[UIImage imageNamed:@"share1@2x"] forState:(UIControlStateNormal)];
    [_rootVC.view addSubview:_shareButton];
    
    _shareLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, _shareButton.width, 19)];
    _shareLabel.text = @"分享";
    _shareLabel.textColor = FMWhite;
    _shareLabel.font = [UIFont systemFontOfSize:12];
    _shareLabel.textAlignment = NSTextAlignmentCenter;
    [_shareButton addSubview:_shareLabel];
    
    //  更多
    _moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _moreButton.frame = CGRectMake(_shareButton.right, kScreenHeight - 49, kScreenWidth / 5, 49);
    [_moreButton setImage:[UIImage imageNamed:@"more1@2x"] forState:(UIControlStateNormal)];
    _moreButton.selected = NO;
    
    [_rootVC.view addSubview:_moreButton];
    
    _moreLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, _commentButton.width, 19)];
    _moreLabel.text = @"更多";
    _moreLabel.textColor = FMWhite;
    _moreLabel.font = [UIFont systemFontOfSize:12];
    _moreLabel.textAlignment = NSTextAlignmentCenter;
    [_moreButton addSubview:_moreLabel];
    
    [_diantaiPlayView.playButton addTarget:self action:@selector(click:) forControlEvents:(UIControlEventTouchUpInside)];
    
}

- (void)click:(UIButton *)btn
{
    if (_isPlayer == YES) {
         [_diantaiPlayView.playButton setBackgroundImage:[UIImage imageNamed:@"play"] forState:(UIControlStateNormal)];
        [_player1 play];
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(playerPlaying:) userInfo:nil repeats:YES];
        _isPlayer = NO;
        [_timer fire];
    }else
    {
        [_diantaiPlayView.playButton setBackgroundImage:[UIImage imageNamed:@"pause"] forState:(UIControlStateNormal)];
        [_player1 pause];
        _isPlayer = YES;
        [_timer invalidate];
    }
}

// slider值改变,滑动改变歌曲进度
- (void)timeChange:(UISlider *)slider {
    [[PKMusicPlayer sharedPlayer] seekToTime:slider.value];
}

// 音乐播放器播放控制,显示时间
- (void)playerPlaying:(NSTimer *)timer {
    NSInteger currentTime = [[PKMusicPlayer sharedPlayer] currentTime];
    NSInteger totalTime = [[PKMusicPlayer sharedPlayer] totalTime];
    NSInteger endTime = totalTime - currentTime;
//    _diantaiPlayView.durationLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",endTime / 60,endTime%60];
    _diantaiPlayView.fmSlider.maximumValue = totalTime;
    _diantaiPlayView.fmSlider.value = currentTime;
    if (endTime == 0 && totalTime != 0) {
        [[PKMusicPlayer sharedPlayer] nextMusic];// 暂停播放
        if (_delegate && [_delegate respondsToSelector:@selector(changeAllViews:)]) {
            [_delegate changeAllViews:[PKMusicPlayer sharedPlayer].index];
        }
    }
    
    if (_model.duration > 0) {
        _diantaiPlayView.durationLabel.text = [NSString stringWithFormat:@"-%ld:%ld",(--_model.duration) / 60,(_model.duration) % 60];
    }
    if (_model.duration == 0) {
        [_player1 pause];
    }
    
    
    [_diantaiPlayView.fmSlider addTarget:self action:@selector(timeChange:) forControlEvents:(UIControlEventValueChanged)];
    
}



#pragma mark --- 网络请求
- (void)requestData
{
    //  千万注意不要在http前添加空格
    NSString  *str = [NSString stringWithFormat:@"http://yiapi.xinli001.com/fm/broadcast-detail-old.json?key=c0d28ec0954084b4426223366293d190&id=%@",_value];
    [PKRequestManager requestWithUrlString:str parDic:nil method:GET finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        _model = [[FMLessonAndFMModel alloc]init];
        [_model setValuesForKeysWithDictionary:dic[@"data"]];
        [_dataDic setValue:_model forKey:@"data"];
        
        
//    //     初始化单例
//        _player = [PKMusicPlayer sharedPlayer];
//        _player.isPlayMainControllerDealloc = NO;
//        _player.userModel.url  = _model.url;
//        if (![_model.url isEqualToString:_player.userModel.url]) {
//            // 给音乐播放列表赋值
//            for (FMLessonAndFMModel *model in _dataDic[@"data"]) {
//                [_musicArray addObject:model];
//            }
//            _player.index = _index;// 给播放器赋值所点击的歌曲index
//            _player.musicArray = _musicArray;
//            [_player play];// 播放歌曲
//        }
        // 播放视频
        _player1 = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:_model.url]];
        [_player1 play];
        //  显示数据
        [_diantaiPlayView.coverImgView sd_setImageWithURL:[NSURL URLWithString:_model.cover] placeholderImage:[UIImage imageNamed:@"fm320"] completed:nil];
        _diantaiPlayView.titleLabel.text = _model.title;
        _diantaiPlayView.viewnumLabel.text = [NSString stringWithFormat:@"收听 %@",_model.viewnum];
        _diantaiPlayView.durationLabel.text = [NSString stringWithFormat:@"-%ld:%ld",_model.duration / 60,_model.duration % 60];
        
        _diantaiPlayView.fmSlider.maximumValue = _model.duration;
        _diantaiPlayView.fmSlider.minimumValue = 0;
        _diantaiPlayView.fmSlider.value = 10;
        
        NSDictionary *speakerDic = _model.diantai;
        [_diantaiPlayView.speakIconButton sd_setBackgroundImageWithURL:[NSURL URLWithString:speakerDic[@"cover"]] forState:(UIControlStateNormal) placeholderImage:nil completed:nil];
        
        _diantaiPlayView.speakNameLabel.text = speakerDic[@"title"];
        _diantaiPlayView.speakContentLabel.text = speakerDic[@"content"];
        
        [_diantaiPlayView.speakIconButton addTarget:self action:@selector(speakIconButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        
        //  为底部点击按钮上的lable赋值
        
        _commentLabel.text = [NSString stringWithFormat:@"评论 %@",_model.commentnum];
        _zanLabel.text = [NSString stringWithFormat:@"赞 %@",_model.favnum];
        
        //  如果请求下来的user_gift_list的这个数组的数量添加按钮
        NSArray *user_gift_listArray = _model.user_gift_list;
        if (user_gift_listArray.count > 0) {
            UILabel *bestNewSendGiftLb = [[UILabel alloc]initWithFrame:CGRectMake(15, _diantaiPlayView.speakIconButton.bottom + 20, 200, 40)];
            bestNewSendGiftLb.text = @"最新送礼";
            [_diantaiPlayView.scrollView addSubview:bestNewSendGiftLb];
            _diantaiPlayView.scrollView.contentSize = CGSizeMake(kScreenWidth, kScreenHeight + 120);
            
            
            
            
        for (int i = 0; i < user_gift_listArray.count; i++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(15 + ((kScreenWidth - 30) / 5 * i), bestNewSendGiftLb.bottom + 10, (kScreenWidth - 30) / 5, 80);
            
            UIImageView *iconImgView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 5, (kScreenWidth - 30) / 5 - 20, (kScreenWidth - 30) / 5 - 20)];
            iconImgView.backgroundColor = FMRed;
            NSDictionary *dic = user_gift_listArray[i];
            [iconImgView sd_setImageWithURL:[NSURL URLWithString:dic[@"avatar"]] placeholderImage:nil completed:nil];
            iconImgView.layer.cornerRadius = iconImgView.width / 2;
            iconImgView.layer.masksToBounds = YES;
            [button addSubview:iconImgView];
            
            UILabel *nicknameLb = [[UILabel alloc]initWithFrame:CGRectMake(5, iconImgView.bottom, (kScreenWidth - 30) / 5 - 10, 20)];
            nicknameLb.text = dic[@"nickname"];
            nicknameLb.font = [UIFont systemFontOfSize:12];
            nicknameLb.textAlignment = NSTextAlignmentCenter;
            nicknameLb.textColor = FMBlack;
            [button addSubview:nicknameLb];
            
            button.tag = [dic[@"id"] intValue
                          
                          ];
            NSLog(@"%ld",(long)button.tag);
            
            [_diantaiPlayView.scrollView addSubview:button];
            
        }

        }

        
        
        
    } error:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark ---  speakIconButton的点击跳转
- (void)speakIconButtonClick:(UIButton *)sender
{
    FMAntorDescViewController *hostVC = [[FMAntorDescViewController alloc]init];
    hostVC.idStr = _model.diantai[@"id"];
    [self.navigationController pushViewController:hostVC animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    //  界面消失前让大的scrollView滑动
    UIScrollView *scrollView = _rootVC.scrollView;
    scrollView.scrollEnabled = YES;
    //  取出tabBar让其隐藏,页面消失时出现
    _rootVC.tabbar.hidden = NO;
    
    _sendGiftButton.hidden = YES;
    _zanButton.hidden = YES;
    _shareButton.hidden = YES;
    _moreButton.hidden = YES;
    _commentButton.hidden = YES;
    [_timer invalidate];

}
#pragma mart ---  返回按钮点击方法
- (void)backButtonClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];

}

#pragma mart ---  底部按钮点击方法
//  送礼物点击
- (void)sendButtonClick:(UIButton *)sender
{
    
}
//  评论点击
- (void)commentButtonClick:(UIButton *)sender
{
    
}
//  赞点击
- (void)zanButtonClick:(UIButton *)sender
{
    
}
//  分享点击
- (void)shareButtonClick:(UIButton *)sender
{
    
}
//  更多点击
- (void)moreButtonClick:(UIButton *)sender
{
    UIButton *button = (UIButton *)sender;
    button.selected = !button.selected;
    if (sender.selected) {
        _moreImgView = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenWidth - 150, _moreButton.top - 140, 140, 140)];
        _moreImgView.image = [UIImage imageNamed:@"more"];
        [self.view addSubview:_moreImgView];
    }else{
        _moreImgView.hidden = YES;
    }
    

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (_moreImgView.hidden == NO) {
        _moreImgView.hidden = YES;

    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
